package com.cgbl.cg.vm.course

import android.app.Application
import androidx.databinding.ObservableField
import api.CourseServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.model.CourseBean
import com.robot.base.model.PageListBean
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class CourseMenuFraViewModel(application: Application): GLBaseViewModel(application) {
    val filterName = ObservableField("全部")
    val list = arrayListOf<String>()
    val type = ObservableField<Int>(0)
    var categoryId = ""

    val tag = ObservableField(true)

    val uc = UiChangeEvent()

    var page = 1
    val pageSize = 10


    class UiChangeEvent {
        val showFilter: SingleLiveEvent<ArrayList<String>> = SingleLiveEvent()
        val dataListEvent: SingleLiveEvent<ArrayList<CourseBean>> = SingleLiveEvent()
        val refreshEvent = SingleLiveEvent<Int>()

    }

    val leftTagCommand = BindingCommand<Any>(BindingAction {
        tag.set(true)
    })

    val rightTagCommand = BindingCommand<Any>(BindingAction {
        tag.set(false)
    })

    val filterCommand = BindingCommand<Any>(BindingAction {
        uc.showFilter.call()
    })

    fun initData(){
        list.addAll(arrayListOf("全部","免费专区","付费专区", "VIP限免"))
    }

    fun refresh(){
        page = 1
        fetchPageInfo()
    }

    fun load(){
        page++
        fetchPageInfo()
    }

    /**
     * isFree 是否免费(2:会员限免1:免费，0:收费)，默认全部
     * sortType 排序类型：0代表按照热度排序，1代表按照时间排序
     */
    fun fetchPageInfo() {
        val params = mapOf(
            "categoryId" to categoryId,
            "isFree" to "",
            "pageNo" to page,
            "pageSize" to pageSize,
            "sortType" to "",
        )
        CourseServiceFactory.page(params).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CourseBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CourseBean>>) {
                uc.dataListEvent.postValue(t.data.list as ArrayList<CourseBean>?)
                uc.refreshEvent.postValue(
                    if (t.data.total.toInt() < page * 10) {
                        0
                    } else {
                        1
                    }
                )
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                uc.refreshEvent.postValue(
                    0
                )
            }
        })
    }
}